<?php

namespace app\company\controller;

use app\BaseController;
use app\model\CompanyConfigModel;
use app\model\CompanyModel;
use app\model\UserModel;
use think\App;
use think\exception\HttpException;

class Company extends BaseController
{
    protected CompanyModel $mode;

    public function __construct(App $app)
    {
        parent::__construct($app);
        if ($this->userData['id'] != 1) throw new HttpException(200, '您没有权限！', null, [], 0);
        $this->mode = new CompanyModel();
    }

    /**
     * 公司列表
     * @return bool|string
     */
    public function list(): bool|string
    {
        try {
            $where = [];
            $data = $this->mode->where($where)->order('id desc')->paginate()->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }


    /**
     * 详情
     * @return bool|string
     */
    public function info(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $data = $this->mode->find($id);
            if (!$data) throw new \Exception('参数错误！');
            $UserModel = new UserModel();
            $data['user'] = $UserModel->field('id,username,password,time')
                ->where([
                    ['company_id', '=', $id],
                    ['type','=',1]
                ])->select()->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 添加
     * @return bool|string
     */
    public function add(): bool|string
    {
        $this->mode->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'name|公司名称'  => 'require',
                'user|账号'  => 'require',
            ]);
            if (isset($param['user'])) {
                $user = $param['user'];
                unset($param['user']);
            }
            if (empty($param['logo'])){
                $param['logo'] = env('SETTING.UNIT_ICON');
            }
            if (empty($param['index_logo'])){
                $param['index_logo'] = env('SETTING.SOFTWARE_LOGO');
            }
            if (empty($param['photo_one'])){
                $param['photo_one'] = env('SETTING.PHOTO_ONE');
            }
            if (empty($param['photo_one'])){
                $param['photo_one'] = env('SETTING.PHOTO_TWO');
            }
            if (empty($param['banner'])){
                $param['banner'] = env('SETTING.PC_BANNER');
            }
            $param['admin_num'] = 999999999;
            $param['consultant_num'] = 999999999;
            $param['user_num'] = 999999999;
            $param['company_num'] = 999999999;
            $param['start_time'] = time();
            $param['end_time'] = 2055909893;
            $param['time'] = time();
            $company_id = $this->mode->insertGetId($param);
            if (!$this->AddDefaultConfig($company_id)) throw new \Exception('默认配置，设置失败！');
            //添加超管
            if (isset($user) && count($user) > 0) {
                $UserModel = new UserModel();
                $usernameData = array_column($user, 'username');
                $id = $UserModel->where('username', 'in', $usernameData)->value('id');
                if ($id) throw new \Exception('账号已存在！');
                $user_save = [];
                foreach ($user as $item) {
                    $this->validate($item, [
                        'username|账号'  =>  'require|length:8,18|alphaNum',
                        'password|密码'  =>  'require|length:8,18',
                    ],[
                        'username.require' => '账号不能为空',
                        'username.length'     => '账号长度不符合要求，8-18位字符',
                        'username.alphaNum'     => '账号格式不符合要求，字母或数字',
                        'password.require'        => '密码不能为空',
                        'password.length'        => '密码长度不符合要求，8-18位字符',
                    ]);
                    $user_save[] = [
                        'company_id' => $company_id,
                        'name' => '超级管理员',
                        'avatar' => '/user_avatar/admin.png',
                        'type' => 1,
                        'username' => $item['username'],
                        'password' => encrypt_password($item['password']),
                        'time' => time()
                    ];
                }
                if (count($user_save) > 0) {
                    $UserModel->insertAll($user_save);
                }
            }
            $this->mode->commit();
            return success([], '添加成功！');
        } catch (\Exception $e) {
            $this->mode->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 编辑
     * @return bool|string
     */
    public function update(): bool|string
    {
        $this->mode->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID'  => 'require',
                'name|公司名称'  => 'require',
                'user|账号'  => 'require',
            ]);
            $info = $this->mode->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $UserModel = new UserModel();
            if (isset($param['user'])) {
                $admin_save = [];
                $usernameData = [];
                foreach ($param['user'] as $item) {
                    $this->validate($item, [
                        'username|账号' => 'require|length:8,18|alphaNum',
                    ], [
                        'username.require' => '账号不能为空',
                        'username.length' => '账号长度不符合要求，8-18位字符',
                        'username.alphaNum' => '账号格式不符合要求，字母或数字',
                    ]);
                    $userInfo = [
                        'company_id' => $param['id'],
                        'name' => '超级管理员',
                        'avatar' => '/user_avatar/admin.png',
                        'type' => 1,
                        'username' => $item['username']
                    ];
                    if (!empty($item['id'])) {
                        if (!empty($item['password'])) {
                            $this->validate($item, [
                                'password|密码' => 'require|length:8,18',
                            ], [
                                'password.require' => '密码不能为空',
                                'password.length' => '密码长度不符合要求，8-18位字符',
                            ]);
                            $userInfo['password'] = encrypt_password($item['password']);
                        }
                        $userInfo['id'] = $item['id'];
                        if (!empty($param['del']) && in_array($item['id'], $param['del'])) {
                            $param['del'] = array_diff($param['del'], [$item['id']]);
                            $userInfo['is_del'] = 1;
                            $userInfo['del_time'] = time();
                        }
                    } else {
                        $this->validate($item, [
                            'password|密码' => 'require|length:8,18',
                        ], [
                            'password.require' => '密码不能为空',
                            'password.length' => '密码长度不符合要求，8-18位字符',
                        ]);
                        $userInfo['password'] = encrypt_password($item['password']);
                        $userInfo['time'] = time();
                        $usernameData[] = $item['username'];
                    }
                    $admin_save[] = $userInfo;
                }
                if (count($admin_save) > 0) {
                    if (count($usernameData) > 0) {
                        $uid = $UserModel->where('username', 'in', $usernameData)->value('id');
                        if ($uid) throw new \Exception('账号已存在！');
                    }
                    $UserModel->saveAll($admin_save);
                }
                unset($param['user']);
            }
            if (isset($param['del'])) {
                if (count($param['del']) > 0) {
                    $UserModel->where('id', 'in', $param['del'])->update([
                        'is_del' => 1,
                        'del_time' => time()
                    ]);
                }
                unset($param['del']);
            }
            $info->save($param);
            $this->mode->commit();
            return success([], '更新成功！');
        } catch (\Exception $e) {
            $this->mode->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 删除
     * @return bool|string
     */
    public function del(): bool|string
    {
        try {
            $this->mode->startTrans();
            $id = $this->request->param('id');
            $info = $this->mode->find($id);
            if (!$info) throw new \Exception('参数错误！');
            $info->save([
                'is_del' => 1,
                'del_time' => time()
            ]);
            $UserModel = new UserModel();
            $UserModel->where([
                ['company_id', '=', $id],
                ['type', '=', 1]
            ])->update([
                'is_del' => 1,
                'del_time' => time()
            ]);
            $this->mode->commit();
            return success([], '删除成功！');
        } catch (\Exception $e) {
            $this->mode->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 封停
     * @return bool|string
     */
    public function status(): bool|string
    {
        $id = $this->request->param('id');
        $status = $this->request->param('status');
        try {
            $this->mode->where('id', '=', $id)->update([
                'status' => $status,
            ]);
            return success([], '修改成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 添加公司默认配置
     * @param $company_id
     * @return int
     */
    public static function AddDefaultConfig($company_id): int
    {
        $time = time();
        $data = [
            [
                'company_id' => $company_id,
                'key' => 'software_settings',
                'value' => '{"news_center":"1","news_type":["1","2","3","4","5","6"],"data_board":"1","enter_board":["1"],"board_verfied":"1","home_todo":["1","2","3","4"],"web_url":"1","screen_protect":"1","is_mobile":"1"}',
                'explain' => '软件设置',
                'time' => $time
            ], [
                'company_id' => $company_id,
                'key' => 'landscape_settings',
                'value' => '[{"id":"25","dot":"1","x":"40","y":"105"},{"id":"26","dot":"1","x":"560","y":"105"},{"id":"27","dot":"1","x":"967","y":"105"},{"id":"28","dot":"1","x":"1380","y":"105"},{"id":"29","dot":"1","x":"40","y":"530"},{"id":"30","dot":"1","x":"560","y":"565"},{"id":"31","dot":"1","x":"1380","y":"460"},{"id":"35","dot":"1","x":"560","y":"320"}]',
                'explain' => '数据大屏设置',
                'time' => $time
            ],
        ];
        $CompanyConfigModel = new CompanyConfigModel();
        return $CompanyConfigModel->insertAll($data);
    }


}
